package com.xyrl.project.app.controller.sales;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xyrl.common.util.ObjectUtil;
import com.xyrl.project.app.util.ShiroUtil;
import com.xyrl.project.common.base.vo.ResponseData;
import com.xyrl.project.common.store.entity.Store;
import com.xyrl.project.common.store.entity.StoreImage;
import com.xyrl.project.common.store.entity.StoreImageMinType;
import com.xyrl.project.common.store.entity.StoreLicense;
import com.xyrl.project.common.store.enu.StoreAuthType;
import com.xyrl.project.common.store.service.StoreAuthService;
import com.xyrl.project.common.store.service.StoreImageService;
import com.xyrl.project.common.store.service.StoreLicenseService;
import com.xyrl.project.common.store.service.StoreService;
import com.xyrl.project.common.store.vo.StoreAuthVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.EnumUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 *@className SaleCustomerController
 *@company 星纭融链科技服务有限公司
 *@author 徐恩源
 *@version 1.0
 *@date 2020-01-02 16:30:58
 *@Description 商户营业执照controller
 */
@Slf4j
@RestController
@RequestMapping("/sales/store/auth")
@Api(value = "商户", tags = "商户模块")
public class SalesStoreAuthController {
    @Autowired
    private StoreService storeService;
    @Autowired
    private StoreLicenseService storeLicenseService;
    @Autowired
    private StoreAuthService storeAuthService;
    @Autowired
    private StoreImageService storeImageService;
    private final int MAX_NUM = 1;
    private final int MAX_BUYER_TRADE_RECORD = 20;
    private final int MAX_BUYER_PIC = 10;
    private final int MAX_SELLER_PIC = 50;

    /**
     * 保存营业执照
     * @author 徐恩源
     * @date 2020-01-07 16:00:58
     * @param storeLicense
     */
    @ApiOperation(value = "保存营业执照", notes = "附件module：storeAuth")
    @PostMapping("/saveStoreLicense")
    public ResponseData saveStoreLicense(@Valid StoreLicense storeLicense) {
       
        Store store = storeService.getById(storeLicense.getId());
        if (null == store || !ShiroUtil.loginUserId().equals(store.getSalesId())) {
            return ResponseData.error("商户不存在");
        }
        storeLicense.setCreateUserId(ShiroUtil.loginUserId());
        storeLicense.setVersion(0);
        storeLicense.setCreateTime(new Date());
        storeLicenseService.saveStoreLicense(storeLicense);
        return ResponseData.success(storeLicense);
    }

    /**
     * 获取营业执照信息
     * @param storeId
     * @return
     */
    @ApiOperation(value = "获取营业执照信息")
    @GetMapping("/getStoreLicense/{storeId}")
    public ResponseData<StoreLicense> getStoreLicense(@PathVariable("storeId") Long storeId) {
       
        Store store = storeService.getById(storeId);
        if (null == store || !ShiroUtil.loginUserId().equals(store.getSalesId())) {
            return ResponseData.error("商户不存在");
        }
        StoreLicense storeLicense = storeLicenseService.getById(storeId);
        return ResponseData.success(storeLicense);
    }
    /**
     * 商户资料
     * @author 徐恩源
     * @date 2020-01-02 14:01:57
     * @param storeId
     */
    @ApiOperation(value = "商户资料", notes = "storeLegal判断是否填写身份证信息")
    @GetMapping("/authInfo/{storeId}")
    public ResponseData authInfo(@PathVariable("storeId") Long storeId) {
       
        StoreAuthVo storeAuthVo = storeAuthService.findStoreAuthVoByStoreId(storeId, ShiroUtil.loginUserId());
        if (null == storeAuthVo) {
            return ResponseData.error("商户不存在");
        }
        return ResponseData.success(storeAuthVo);
    }
    /**
     * 认证图片上传
     * @author 徐恩源
     * @date 2020-01-06 11:11:55
     * @param storeId
     * @param storeAuthType
     * @param attIds
     */
    @ApiOperation(value = "认证图片上传", notes = "附件module：storeAuth")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "storeAuthType", value = "buyerTradeRecord|交易流水，sellerPic|供货商资质")
    })
    @PostMapping("/saveAuthImage")
    public ResponseData saveAuthImage(@RequestParam(name = "storeId") Long storeId,
                                      @RequestParam(name = "storeAuthType") StoreAuthType storeAuthType,
                                      @RequestParam(name = "attIds") Long[] attIds) {
        Long salesId = ShiroUtil.loginUserId();
        Store store = storeService.getById(storeId);
        if (null == store || !salesId.equals(store.getSalesId())) {
            return ResponseData.error("商户不存在");
        }
        if (StoreAuthType.buyerTradeRecord.equals(storeAuthType)) {
            if (attIds.length > MAX_BUYER_TRADE_RECORD) {
                return ResponseData.error(" 交易流水图片数量不能超过" + MAX_BUYER_TRADE_RECORD + "张");
            }
        } else if (StoreAuthType.sellerPic.equals(storeAuthType)) {
            if (attIds.length > MAX_SELLER_PIC) {
                return ResponseData.error("供货商资质图片数量不能超过" + MAX_SELLER_PIC + "张");
            }
        } else {
            return ResponseData.error("参数错误");
        }
        storeAuthService.updateStoreAuth(storeId, salesId, storeAuthType, attIds);
        return ResponseData.success();
    }
    /**
     * 门店图片认证
     * @author 徐恩源
     * @date 2020-01-06 11:09:08
     * @param storeId
     */
    @ApiOperation(value = "认证图片上传", notes = "附件module：storeAuth")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "first", value = "门头照片"),
            @ApiImplicitParam(name = "two", value = "收银台照片"),
            @ApiImplicitParam(name = "three", value = "内景照片1"),
            @ApiImplicitParam(name = "four", value = "内景照片2"),
            @ApiImplicitParam(name = "five", value = "其他照片"),
    })
    @PostMapping("/saveStoreImage")
    public ResponseData saveStoreImage(long storeId,Long[] five, HttpServletRequest request) {
        Map<String, String[]> map = request.getParameterMap();
        Store store = storeService.getById(storeId);
        if (null == store || !ShiroUtil.loginUserId().equals(store.getSalesId())) {
            return ResponseData.error("商户不存在");
        }
        List<StoreImage> imageList = new ArrayList<>();
        if (ObjectUtil.isNotEmpty(five)) {
            if (five.length > MAX_BUYER_PIC) {
                return ResponseData.error("门店照片认证，其他图片数量不能超过" + MAX_BUYER_PIC + "张");
            }
            for (Long attId : five) {
                StoreImage storeImage = new StoreImage();
                storeImage.setCreateTime(new Date());
                storeImage.setStoreId(storeId);
                storeImage.setType(StoreAuthType.buyerStorePic.name());
                storeImage.setAttId(attId);
                storeImage.setMinType(StoreImageMinType.five.name());
                imageList.add(storeImage);
            }
        }

        for (String key : map.keySet()) {
            StoreImageMinType imageMinType = EnumUtils.getEnum(StoreImageMinType.class, key);
            if (null == imageMinType|| StoreImageMinType.five.equals(imageMinType)) {
                continue;
            }
            String[] attIds = map.get(key);
            if (ObjectUtil.isEmpty(attIds)) {
                continue;
            }
            if (attIds.length > MAX_NUM) {
                return ResponseData.error("门店照片认证，图片数量不能超过" + MAX_NUM + "张");
            }
            for (String attId : attIds) {
                StoreImage storeImage = new StoreImage();
                storeImage.setCreateTime(new Date());
                storeImage.setStoreId(storeId);
                storeImage.setType(StoreAuthType.buyerStorePic.name());
                storeImage.setAttId(Long.valueOf(attId));
                storeImage.setMinType(key);
                imageList.add(storeImage);
            }
        }


        storeAuthService.updateStoreAuth(ShiroUtil.loginUserId(), storeId, imageList);
        return ResponseData.success();
    }

    @ApiImplicitParam(name = "storeAuthType", value = "buyerTradeRecord|交易流水，sellerPic|供货商资质，buyerStorePic|门店照片认证")
    @ApiOperation(value = "获取认证图片")
    @PostMapping("/getAuthImage")
    public ResponseData getAuthImage(@RequestParam(name = "storeId") Long storeId,
                                     @RequestParam(name = "storeAuthType") StoreAuthType storeAuthType) {
       
        Store store = storeService.getById(storeId);
        if (null == store || !ShiroUtil.loginUserId().equals(store.getSalesId())) {
            return ResponseData.error("商户不存在");
        }
        LambdaQueryWrapper<StoreImage> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(StoreImage::getStoreId,storeId);
        wrapper.eq(StoreImage::getType,storeAuthType.name());
        List<StoreImage> list = storeImageService.list(wrapper);
        return ResponseData.success(list);
    }
}
